import { useModelConfigStore } from '@/stores/modelConfig'
import type { ModelConfig } from '@/stores/modelConfig'
import aiRequest from '@/utils/aiRequest'

export interface ChatMessage {
  role: 'system' | 'user' | 'assistant'
  content: string
}

export interface ChatResponse {
  content: string
  usage: {
    prompt_tokens: number
    completion_tokens: number
    total_tokens: number
  }
  cost?: number
  duration: number
}

export interface GenerateOptions {
  systemPrompt?: string
  userPrompt: string
  config?: Partial<ModelConfig>
}

class AIServiceManager {
  private getHeaders(provider: string, apiKey: string): Record<string, string> {
    const headers: Record<string, string> = {
      'Content-Type': 'application/json'
    }

    switch (provider) {
      case 'qwen':
        headers['Authorization'] = `Bearer ${apiKey}`
        break
      case 'doubao':
        headers['Authorization'] = `Bearer ${apiKey}`
        break
      case 'deepseek':
        headers['Authorization'] = `Bearer ${apiKey}`
        break
      default:
        headers['Authorization'] = `Bearer ${apiKey}`
    }

    return headers
  }

  private getEndpoint(provider: string): string {
    // 使用本地代理端点避免CORS问题
    const endpoints = {
      'qwen': '/api/ai/qwen',
      'doubao': '/api/ai/doubao', 
      'deepseek': '/api/ai/deepseek'
    }
    
    return endpoints[provider as keyof typeof endpoints] || endpoints.qwen
  }

  private buildRequestPayload(provider: string, model: string, messages: ChatMessage[], config: ModelConfig) {
    const basePayload = {
      model,
      messages,
      temperature: config.temperature,
      max_tokens: config.maxTokens,
      top_p: config.topP,
      frequency_penalty: config.frequencyPenalty,
      presence_penalty: config.presencePenalty,
      stream: false
    }

    // 不同提供商的请求格式可能略有不同
    switch (provider) {
      case 'qwen':
        return {
          model,
          input: {
            messages,
          },
          parameters: {
            temperature: config.temperature,
            max_tokens: config.maxTokens,
            top_p: config.topP,
            result_format: 'message'
          }
        }
      case 'doubao':
      case 'deepseek':
      default:
        return basePayload
    }
  }

  private parseResponse(provider: string, response: any): { content: string; usage: any } {
    switch (provider) {
      case 'qwen':
        return {
          content: response.output?.choices?.[0]?.message?.content || response.output?.text || '',
          usage: response.usage || { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 }
        }
      case 'doubao':
      case 'deepseek':
      default:
        return {
          content: response.choices?.[0]?.message?.content || '',
          usage: response.usage || { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 }
        }
    }
  }

  private calculateCost(provider: string, model: string, usage: any): number {
    const costPerK = {
      'qwen': { 'qwen-plus-latest': 0.002, 'qwen-turbo-latest': 0.001 },
      'doubao': { 'doubao-seed-1-6-250615': 0.0015 },
      'deepseek': { 'deepseek-reasoner': 0.0008, 'deepseek-chat': 0.0008 }
    }

    const providerCost = costPerK[provider as keyof typeof costPerK]
    if (!providerCost) return 0

    const modelCost = providerCost[model as keyof typeof providerCost]
    if (!modelCost) return 0

    return (usage.total_tokens / 1000) * modelCost
  }

  async chat(messages: ChatMessage[], options: { config?: Partial<ModelConfig> } = {}): Promise<ChatResponse> {
    const modelStore = useModelConfigStore()
    const startTime = Date.now()
    
    // 合并配置
    const finalConfig: ModelConfig = {
      ...modelStore.globalConfig,
      ...options.config
    }

    const currentProvider = modelStore.getCurrentProvider()
    if (!currentProvider) {
      throw new Error('未选择AI模型提供商')
    }

    const apiKey = currentProvider.apiKey
    if (!apiKey) {
      throw new Error(`请配置${currentProvider.name}的API密钥`)
    }

    try {
      const endpoint = this.getEndpoint(finalConfig.provider)
      const headers = this.getHeaders(finalConfig.provider, apiKey)
      const payload = this.buildRequestPayload(
        finalConfig.provider,
        finalConfig.model,
        messages,
        finalConfig
      )

      const response = await aiRequest.post(endpoint, payload, {
        headers,
        timeout: 60000
      })

      const parsed = this.parseResponse(finalConfig.provider, response.data)
      const duration = Date.now() - startTime
      const cost = this.calculateCost(finalConfig.provider, finalConfig.model, parsed.usage)

      return {
        content: parsed.content,
        usage: parsed.usage,
        cost,
        duration
      }
    } catch (error) {
      const duration = Date.now() - startTime
      
      if (error instanceof Error) {
        throw new Error(`AI服务调用失败: ${error.message}`)
      }
      
      throw new Error(`AI服务调用失败: ${String(error)}`)
    }
  }

  async generateText(options: GenerateOptions): Promise<ChatResponse> {
    const messages: ChatMessage[] = []
    
    if (options.systemPrompt) {
      messages.push({
        role: 'system',
        content: options.systemPrompt
      })
    }
    
    messages.push({
      role: 'user',
      content: options.userPrompt
    })

    return this.chat(messages, { config: options.config })
  }

  async testConnection(provider?: string): Promise<{ success: boolean; message: string; latency?: number }> {
    const modelStore = useModelConfigStore()
    const targetProvider = provider ? modelStore.providers[provider] : modelStore.getCurrentProvider()
    
    if (!targetProvider) {
      return { success: false, message: '未找到指定的模型提供商' }
    }

    if (!targetProvider.hasApiKey) {
      return { success: false, message: 'API密钥未配置' }
    }

    try {
      const testMessages: ChatMessage[] = [
        { role: 'user', content: '请回复"连接测试成功"' }
      ]

      const startTime = Date.now()
      const response = await this.chat(testMessages, {
        config: {
          provider: targetProvider.id,
          model: targetProvider.models[0].id,
          temperature: 0.1,
          maxTokens: 50
        }
      })

      return {
        success: true,
        message: '连接测试成功',
        latency: Date.now() - startTime
      }
    } catch (error) {
      return {
        success: false,
        message: error instanceof Error ? error.message : String(error)
      }
    }
  }
}

// 导出单例实例
export const aiService = new AIServiceManager()